from BaseClass import *
from sqlalchemy.orm import sessionmaker
from utils import engine
from utils import *

Session = sessionmaker(bind=engine)
db_session = Session()


def addData(Participle):
    ''' 添加数据 '''
    try:
        db_session.add(Participle)
        db_session.commit()
        return True
    except Exception as e:
        print(e)
        db_session.rollback()
        return False


'''查询类型'''


def findSyType():
    results = db_session.query(symptomType).all()
    results_list = []
    for rlt in results:
        results_list.append({"id": rlt.id, "name": rlt.name})
    return results_list


'''查询所有方剂'''


def findallfj():
    results = db_session.query(Prescription).all()
    return model_to_dict(results)


'''修改方剂'''


def modfyPrescription(id, *pre):
    print(pre)
    try:
        data = db_session.query(Prescription).filter(Prescription.id == id).first()
        data.init(*pre[0])

        db_session.commit()
        return True
    except Exception as e:
        print(e)
        db_session.rollback()
        return False


'''根据id查询方剂'''


def findPrescriptionById(id):
    data = db_session.query(Prescription).filter(Prescription.id == id).first()
    return data.get_model_dict()


# 根据关键词模糊查询
def findWordBySpell(spell):
    result = db_session.query(Participle).filter(Participle.spell.like(f'%{spell}%')).all()
    lit = []
    for i in result:
        lit.append(i.to_dict())
    return lit


def insert_data(data):
    """添加数据"""
    try:
        db_session.add(data)
        db_session.commit()
        return data.id
    except Exception as e:
        print(e)
        db_session.rollback()
        return False


def get_book_list():
    """获取书籍列表"""
    try:
        result = db_session.query(Book).filter().all()
        return serialize(result)
    except Exception as e:
        print(e)
        return -1


def get_chapter_by_book_id(book_id):
    """根据书籍id获取章节列表"""
    try:
        return serialize(db_session.query(Chapter).filter(Chapter.book_id == book_id).all())
    except Exception as e:
        print(e)
        return -1


def get_content_by_chapter_id(chapter_id):
    """根据章节id获取内容列表"""
    try:
        return serialize(db_session.query(Content).filter(Content.chapter_id == chapter_id).all())
    except Exception as e:
        print(e)
        return -1


def get_symptom_list():
    return get_except(db_session.query(Symptom).filter().all())


def update_symptom_by_id(new_symptom: Symptom):
    try:
        old = db_session.query(Symptom).filter(Symptom.id == new_symptom.id).first()
        old = new_symptom
        db_session.commit()
    except Exception as e:
        print(e)
        return -1


def get_treat_by_symptom_id(symptom_id):
    return get_except(db_session.query(Treat).filter(Treat.symptom_id == symptom_id).all())


def update_treat_by_id(new_treat: Treat):
    try:
        old = db_session.query(Treat).filter(Treat.id == new_treat.id).first()
        old = new_treat
        db_session.commit()
        return new_treat.id
    except Exception as e:
        print(e)
        return -1


'''将查询结果转成字典'''


def model_to_dict(result):
    from collections import Iterable
    # 转换完成后，删除  '_sa_instance_state' 特殊属性
    try:
        if isinstance(result, Iterable):
            tmp = [dict(zip(res.__dict__.keys(), res.__dict__.values())) for res in result]
            for t in tmp:
                t.pop('_sa_instance_state')
                t.pop('isExists')
        else:
            tmp = dict(zip(result.__dict__.keys(), result.__dict__.values()))
            tmp.pop('_sa_instance_state')
        return tmp
    except BaseException as e:
        print(e.args)
        raise TypeError('Type error of parameter')


def get_except(data_base):
    """异常方法"""
    try:
        return serialize(data_base)
    except Exception as e:
        print(e)
        return -1


# def update_except(data_base):
#     try:
#


if __name__ == '__main__':
    # findWordBySpell("f")
    # print(findSyType())
    # p = Prescription()
    # p.name = "艾附暖宫丸"
    # p.ancient = "艾叶（炭）120g ,香附（醋制）240g ,吴茱萸（制）80g ,肉桂20g, 当归120g ,川芎80g, 白芍（酒炒）80g ,地黄40g, 黄芪（蜜炙）80g ,续断60g"
    # p.major= "理气补血，暖宫调经。用于子宫虚寒，月经不调，经来腹痛，腰酸带下"
    # p.song = "test"
    # print(modfyPrescription(4, p))
    # p = ['测试222', '测试', '测试测试', '测试测试', '测试测试', '测试', '测试', '测试', '测试', '', '', '']
    # print(modfyPrescription(15, p))

    # print(findallfj())
    str = "口唇色淡，爪甲无泽，头晕耳鸣，两目干涩，面部烘热，胁肋隐痛，五心烦热，潮热盗汗，咽干口燥，舌红少津，少苔或无苔，脉细数".split("，")
    for word in str:
        sp = chineseToSpell(word)
        p =Participle()
        p.init(sp,word,"测试")
        addData(p)

